import os
import json
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QTableWidget, 
                             QTableWidgetItem, QPushButton, QLabel, QSpinBox,
                             QTimeEdit, QTextEdit, QComboBox, QColorDialog,
                             QFontDialog, QGroupBox, QSplitter, QHeaderView,
                             QMessageBox, QFileDialog, QSlider)
from PyQt5.QtCore import Qt, QTime, pyqtSignal, QTimer
from PyQt5.QtGui import QFont, QColor, QPalette
import pysrt


class SubtitleEditor(QWidget):
    """字幕编辑器主界面"""
    
    subtitle_changed = pyqtSignal(list)  # 字幕变化信号
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.subtitles = []  # 字幕列表
        self.current_subtitle_index = -1
        self.init_ui()
        self.load_default_subtitles()
        
    def init_ui(self):
        """初始化用户界面"""
        main_layout = QVBoxLayout()
        
        # 顶部工具栏
        toolbar = QHBoxLayout()
        
        # 文件操作按钮
        self.load_btn = QPushButton("加载字幕文件")
        self.load_btn.clicked.connect(self.load_subtitle_file)
        self.save_btn = QPushButton("保存字幕文件")
        self.save_btn.clicked.connect(self.save_subtitle_file)
        self.export_btn = QPushButton("导出视频")
        self.export_btn.clicked.connect(self.export_video_with_subtitles)
        
        toolbar.addWidget(self.load_btn)
        toolbar.addWidget(self.save_btn)
        toolbar.addWidget(self.export_btn)
        toolbar.addStretch()
        
        # 字幕样式设置
        self.font_btn = QPushButton("字体设置")
        self.font_btn.clicked.connect(self.set_font)
        self.color_btn = QPushButton("颜色设置")
        self.color_btn.clicked.connect(self.set_color)
        
        toolbar.addWidget(self.font_btn)
        toolbar.addWidget(self.color_btn)
        
        main_layout.addLayout(toolbar)
        
        # 主分割器
        splitter = QSplitter(Qt.Horizontal)
        
        # 左侧字幕列表
        left_widget = QWidget()
        left_layout = QVBoxLayout()
        
        # 字幕列表标题
        subtitle_list_label = QLabel("字幕列表")
        subtitle_list_label.setFont(QFont("Arial", 12, QFont.Bold))
        left_layout.addWidget(subtitle_list_label)
        
        # 字幕表格
        self.subtitle_table = QTableWidget()
        self.subtitle_table.setColumnCount(4)
        self.subtitle_table.setHorizontalHeaderLabels(["序号", "开始时间", "结束时间", "字幕内容"])
        self.subtitle_table.horizontalHeader().setSectionResizeMode(3, QHeaderView.Stretch)
        self.subtitle_table.setSelectionBehavior(QTableWidget.SelectRows)
        self.subtitle_table.itemSelectionChanged.connect(self.on_subtitle_selected)
        left_layout.addWidget(self.subtitle_table)
        
        # 字幕操作按钮
        subtitle_btn_layout = QHBoxLayout()
        self.add_btn = QPushButton("添加字幕")
        self.add_btn.clicked.connect(self.add_subtitle)
        self.delete_btn = QPushButton("删除字幕")
        self.delete_btn.clicked.connect(self.delete_subtitle)
        self.move_up_btn = QPushButton("上移")
        self.move_up_btn.clicked.connect(self.move_subtitle_up)
        self.move_down_btn = QPushButton("下移")
        self.move_down_btn.clicked.connect(self.move_subtitle_down)
        
        subtitle_btn_layout.addWidget(self.add_btn)
        subtitle_btn_layout.addWidget(self.delete_btn)
        subtitle_btn_layout.addWidget(self.move_up_btn)
        subtitle_btn_layout.addWidget(self.move_down_btn)
        left_layout.addLayout(subtitle_btn_layout)
        
        left_widget.setLayout(left_layout)
        splitter.addWidget(left_widget)
        
        # 右侧编辑区域
        right_widget = QWidget()
        right_layout = QVBoxLayout()
        
        # 字幕编辑标题
        edit_label = QLabel("字幕编辑")
        edit_label.setFont(QFont("Arial", 12, QFont.Bold))
        right_layout.addWidget(edit_label)
        
        # 时间编辑组
        time_group = QGroupBox("时间设置")
        time_layout = QVBoxLayout()
        
        # 开始时间
        start_time_layout = QHBoxLayout()
        start_time_layout.addWidget(QLabel("开始时间:"))
        self.start_time_edit = QTimeEdit()
        self.start_time_edit.setDisplayFormat("HH:mm:ss.zzz")
        self.start_time_edit.timeChanged.connect(self.on_start_time_changed)
        start_time_layout.addWidget(self.start_time_edit)
        time_layout.addLayout(start_time_layout)
        
        # 结束时间
        end_time_layout = QHBoxLayout()
        end_time_layout.addWidget(QLabel("结束时间:"))
        self.end_time_edit = QTimeEdit()
        self.end_time_edit.setDisplayFormat("HH:mm:ss.zzz")
        self.end_time_edit.timeChanged.connect(self.on_end_time_changed)
        end_time_layout.addWidget(self.end_time_edit)
        time_layout.addLayout(end_time_layout)
        
        # 持续时间
        duration_layout = QHBoxLayout()
        duration_layout.addWidget(QLabel("持续时间:"))
        self.duration_label = QLabel("00:00:00.000")
        duration_layout.addWidget(self.duration_label)
        duration_layout.addStretch()
        time_layout.addLayout(duration_layout)
        
        time_group.setLayout(time_layout)
        right_layout.addWidget(time_group)
        
        # 字幕内容编辑
        content_group = QGroupBox("字幕内容")
        content_layout = QVBoxLayout()
        
        self.content_edit = QTextEdit()
        self.content_edit.setMaximumHeight(100)
        self.content_edit.textChanged.connect(self.on_content_changed)
        content_layout.addWidget(self.content_edit)
        
        content_group.setLayout(content_layout)
        right_layout.addWidget(content_group)
        
        # 样式预览
        preview_group = QGroupBox("样式预览")
        preview_layout = QVBoxLayout()
        
        self.preview_label = QLabel("字幕预览效果")
        self.preview_label.setAlignment(Qt.AlignCenter)
        self.preview_label.setMinimumHeight(80)
        self.preview_label.setStyleSheet("""
            QLabel {
                background-color: rgba(0, 0, 0, 0.8);
                color: white;
                border: 2px solid white;
                border-radius: 10px;
                padding: 10px;
            }
        """)
        preview_layout.addWidget(self.preview_label)
        
        preview_group.setLayout(preview_layout)
        right_layout.addWidget(preview_group)
        
        right_widget.setLayout(right_layout)
        splitter.addWidget(right_widget)
        
        # 设置分割器比例
        splitter.setSizes([400, 600])
        main_layout.addWidget(splitter)
        
        self.setLayout(main_layout)
        
        # 初始化样式
        self.subtitle_font = QFont("Arial", 24)
        self.subtitle_color = QColor(255, 255, 255)
        self.subtitle_outline_color = QColor(0, 0, 0)
        self.subtitle_outline_width = 2
        
        # 更新预览
        self.update_preview()
        
    def load_default_subtitles(self):
        """加载默认字幕示例"""
        sample_subtitles = [
            {"start": "00:00:01,000", "end": "00:00:04,000", "text": "欢迎使用字幕编辑器"},
            {"start": "00:00:05,000", "end": "00:00:08,000", "text": "您可以在这里编辑字幕内容和时间"},
            {"start": "00:00:09,000", "end": "00:00:12,000", "text": "支持多种字幕格式和样式设置"}
        ]
        
        for subtitle in sample_subtitles:
            self.add_subtitle_from_dict(subtitle)
            
    def add_subtitle_from_dict(self, subtitle_dict):
        """从字典添加字幕"""
        start_time = self.parse_time_string(subtitle_dict["start"])
        end_time = self.parse_time_string(subtitle_dict["end"])
        
        subtitle = {
            "start": start_time,
            "end": end_time,
            "text": subtitle_dict["text"]
        }
        
        self.subtitles.append(subtitle)
        self.update_subtitle_table()
        
    def parse_time_string(self, time_str):
        """解析时间字符串为QTime对象"""
        # 支持格式: HH:mm:ss,mmm 或 HH:mm:ss.mmm
        time_str = time_str.replace(",", ".")
        parts = time_str.split(":")
        
        if len(parts) == 3:
            hours = int(parts[0])
            minutes = int(parts[1])
            seconds_ms = parts[2].split(".")
            seconds = int(seconds_ms[0])
            milliseconds = int(seconds_ms[1]) if len(seconds_ms) > 1 else 0
            
            return QTime(hours, minutes, seconds, milliseconds * 10)
        
        return QTime(0, 0, 0, 0)
        
    def update_subtitle_table(self):
        """更新字幕表格"""
        self.subtitle_table.setRowCount(len(self.subtitles))
        
        for row, subtitle in enumerate(self.subtitles):
            # 序号
            index_item = QTableWidgetItem(str(row + 1))
            index_item.setFlags(index_item.flags() & ~Qt.ItemIsEditable)
            self.subtitle_table.setItem(row, 0, index_item)
            
            # 开始时间
            start_item = QTableWidgetItem(subtitle["start"].toString("HH:mm:ss.zzz"))
            start_item.setFlags(start_item.flags() & ~Qt.ItemIsEditable)
            self.subtitle_table.setItem(row, 1, start_item)
            
            # 结束时间
            end_item = QTableWidgetItem(subtitle["end"].toString("HH:mm:ss.zzz"))
            end_item.setFlags(end_item.flags() & ~Qt.ItemIsEditable)
            self.subtitle_table.setItem(row, 2, end_item)
            
            # 字幕内容
            text_item = QTableWidgetItem(subtitle["text"])
            self.subtitle_table.setItem(row, 3, text_item)
            
        self.subtitle_changed.emit(self.subtitles)
        
    def on_subtitle_selected(self):
        """字幕选择变化事件"""
        current_row = self.subtitle_table.currentRow()
        if current_row >= 0 and current_row < len(self.subtitles):
            self.current_subtitle_index = current_row
            self.load_subtitle_to_editor(current_row)
            
    def load_subtitle_to_editor(self, index):
        """加载字幕到编辑器"""
        if 0 <= index < len(self.subtitles):
            subtitle = self.subtitles[index]
            
            # 更新时间编辑
            self.start_time_edit.setTime(subtitle["start"])
            self.end_time_edit.setTime(subtitle["end"])
            
            # 更新内容编辑
            self.content_edit.setPlainText(subtitle["text"])
            
            # 更新持续时间
            self.update_duration()
            
    def update_duration(self):
        """更新持续时间显示"""
        start_time = self.start_time_edit.time()
        end_time = self.end_time_edit.time()
        
        start_ms = start_time.msecsSinceStartOfDay()
        end_ms = end_time.msecsSinceStartOfDay()
        duration_ms = end_ms - start_ms
        
        if duration_ms >= 0:
            duration_time = QTime(0, 0, 0, 0).addMSecs(duration_ms)
            self.duration_label.setText(duration_time.toString("HH:mm:ss.zzz"))
        else:
            self.duration_label.setText("00:00:00.000")
            
    def on_start_time_changed(self):
        """开始时间变化事件"""
        if self.current_subtitle_index >= 0:
            self.update_duration()
            self.update_subtitle_time()
            
    def on_end_time_changed(self):
        """结束时间变化事件"""
        if self.current_subtitle_index >= 0:
            self.update_duration()
            self.update_subtitle_time()
            
    def on_content_changed(self):
        """内容变化事件"""
        if self.current_subtitle_index >= 0:
            self.update_subtitle_content()
            self.update_preview()
            
    def update_subtitle_time(self):
        """更新字幕时间"""
        if self.current_subtitle_index >= 0:
            start_time = self.start_time_edit.time()
            end_time = self.end_time_edit.time()
            
            self.subtitles[self.current_subtitle_index]["start"] = start_time
            self.subtitles[self.current_subtitle_index]["end"] = end_time
            
            # 更新表格显示
            start_item = QTableWidgetItem(start_time.toString("HH:mm:ss.zzz"))
            start_item.setFlags(start_item.flags() & ~Qt.ItemIsEditable)
            self.subtitle_table.setItem(self.current_subtitle_index, 1, start_item)
            
            end_item = QTableWidgetItem(end_time.toString("HH:mm:ss.zzz"))
            end_item.setFlags(end_item.flags() & ~Qt.ItemIsEditable)
            self.subtitle_table.setItem(self.current_subtitle_index, 2, end_item)
            
            self.subtitle_changed.emit(self.subtitles)
            
    def update_subtitle_content(self):
        """更新字幕内容"""
        if self.current_subtitle_index >= 0:
            content = self.content_edit.toPlainText()
            self.subtitles[self.current_subtitle_index]["text"] = content
            
            # 更新表格显示
            text_item = QTableWidgetItem(content)
            self.subtitle_table.setItem(self.current_subtitle_index, 3, text_item)
            
            self.subtitle_changed.emit(self.subtitles)
            
    def add_subtitle(self):
        """添加新字幕"""
        # 计算新字幕的时间
        if self.subtitles:
            last_end = self.subtitles[-1]["end"]
            new_start = QTime(0, 0, 0, 0).addMSecs(last_end.msecsSinceStartOfDay() + 1000)
            new_end = QTime(0, 0, 0, 0).addMSecs(last_end.msecsSinceStartOfDay() + 4000)
        else:
            new_start = QTime(0, 0, 1, 0)
            new_end = QTime(0, 0, 4, 0)
            
        new_subtitle = {
            "start": new_start,
            "end": new_end,
            "text": "新字幕"
        }
        
        self.subtitles.append(new_subtitle)
        self.update_subtitle_table()
        
        # 选择新字幕
        self.subtitle_table.selectRow(len(self.subtitles) - 1)
        
    def delete_subtitle(self):
        """删除选中的字幕"""
        if self.current_subtitle_index >= 0:
            del self.subtitles[self.current_subtitle_index]
            self.current_subtitle_index = -1
            self.update_subtitle_table()
            
            # 清空编辑器
            self.start_time_edit.setTime(QTime(0, 0, 0, 0))
            self.end_time_edit.setTime(QTime(0, 0, 0, 0))
            self.content_edit.clear()
            self.duration_label.setText("00:00:00.000")
            
    def move_subtitle_up(self):
        """上移字幕"""
        if self.current_subtitle_index > 0:
            self.subtitles[self.current_subtitle_index], self.subtitles[self.current_subtitle_index - 1] = \
                self.subtitles[self.current_subtitle_index - 1], self.subtitles[self.current_subtitle_index]
            
            self.current_subtitle_index -= 1
            self.update_subtitle_table()
            self.subtitle_table.selectRow(self.current_subtitle_index)
            
    def move_subtitle_down(self):
        """下移字幕"""
        if self.current_subtitle_index >= 0 and self.current_subtitle_index < len(self.subtitles) - 1:
            self.subtitles[self.current_subtitle_index], self.subtitles[self.current_subtitle_index + 1] = \
                self.subtitles[self.current_subtitle_index + 1], self.subtitles[self.current_subtitle_index]
            
            self.current_subtitle_index += 1
            self.update_subtitle_table()
            self.subtitle_table.selectRow(self.current_subtitle_index)
            
    def set_font(self):
        """设置字体"""
        font, ok = QFontDialog.getFont(self.subtitle_font, self)
        if ok:
            self.subtitle_font = font
            self.update_preview()
            
    def set_color(self):
        """设置颜色"""
        color = QColorDialog.getColor(self.subtitle_color, self)
        if color.isValid():
            self.subtitle_color = color
            self.update_preview()
            
    def update_preview(self):
        """更新预览效果"""
        if self.current_subtitle_index >= 0:
            content = self.subtitles[self.current_subtitle_index]["text"]
        else:
            content = "字幕预览效果"
            
        # 设置预览标签的字体和颜色
        self.preview_label.setFont(self.subtitle_font)
        self.preview_label.setText(content)
        
        # 设置样式
        style = f"""
            QLabel {{
                background-color: rgba(0, 0, 0, 0.8);
                color: {self.subtitle_color.name()};
                border: {self.subtitle_outline_width}px solid {self.subtitle_outline_color.name()};
                border-radius: 10px;
                padding: 10px;
            }}
        """
        self.preview_label.setStyleSheet(style)
        
    def load_subtitle_file(self):
        """加载字幕文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择字幕文件", "", 
            "字幕文件 (*.srt *.ass *.ssa);;所有文件 (*.*)"
        )
        
        if file_path:
            try:
                if file_path.endswith('.srt'):
                    self.load_srt_file(file_path)
                else:
                    QMessageBox.warning(self, "警告", "目前只支持SRT格式字幕文件")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"加载字幕文件失败: {str(e)}")
                
    def load_srt_file(self, file_path):
        """加载SRT字幕文件"""
        subs = pysrt.open(file_path)
        self.subtitles.clear()
        
        for sub in subs:
            start_time = QTime(0, 0, 0, 0).addMSecs(sub.start.ordinal)
            end_time = QTime(0, 0, 0, 0).addMSecs(sub.end.ordinal)
            
            subtitle = {
                "start": start_time,
                "end": end_time,
                "text": sub.text
            }
            self.subtitles.append(subtitle)
            
        self.update_subtitle_table()
        QMessageBox.information(self, "成功", f"成功加载 {len(self.subtitles)} 条字幕")
        
    def save_subtitle_file(self):
        """保存字幕文件"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存字幕文件", "", 
            "SRT字幕文件 (*.srt);;所有文件 (*.*)"
        )
        
        if file_path:
            try:
                self.save_srt_file(file_path)
                QMessageBox.information(self, "成功", "字幕文件保存成功")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存字幕文件失败: {str(e)}")
                
    def save_srt_file(self, file_path):
        """保存为SRT格式"""
        with open(file_path, 'w', encoding='utf-8') as f:
            for i, subtitle in enumerate(self.subtitles):
                # 序号
                f.write(f"{i + 1}\n")
                
                # 时间
                start_str = subtitle["start"].toString("HH:mm:ss,zzz").replace(".", ",")
                end_str = subtitle["end"].toString("HH:mm:ss,zzz").replace(".", ",")
                f.write(f"{start_str} --> {end_str}\n")
                
                # 内容
                f.write(f"{subtitle['text']}\n\n")
                
    def export_video_with_subtitles(self):
        """导出带字幕的视频"""
        # 这里需要实现视频导出功能
        QMessageBox.information(self, "提示", "视频导出功能将在后续版本中实现")
        
    def get_subtitles(self):
        """获取字幕列表"""
        return self.subtitles 